﻿// Copyright (c) 2021 Siegfried Pammer
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ICSharpCode.Decompiler.TypeSystem;

namespace ICSharpCode.Decompiler.IL.Transforms
{
	// stloc s(ldloca v)
	// stobj System.DateTime(ldloc s, default.value T)
	// where s.LoadCount > 1
	// which is: ldloca; dup; initobj in IL (generated by Roslyn >= 2)
	// =>
	// stloc v(default.value T)
	// stloc s(ldloca v)
	// which is: ldloca; ldloca; initobj in IL (generated by legacy csc)
	// 
	// The second pattern allows inlining in the subsequent uses.
	class LdLocaDupInitObjTransform : IILTransform
	{
		void IILTransform.Run(ILFunction function, ILTransformContext context)
		{
			foreach (var block in function.Descendants.OfType<Block>())
			{
				for (int i = 0; i < block.Instructions.Count; i++)
				{
					TryTransform(block, i, context);
				}
			}
		}

		private bool TryTransform(Block block, int i, ILTransformContext context)
		{
			if (block.Instructions[i] is not StLoc { Variable: var s, Value: LdLoca { Variable: var v } } inst1)
			{
				return false;
			}
			if (block.Instructions.ElementAtOrDefault(i + 1) is not StObj inst2)
			{
				return false;
			}
			if (!(inst2.Target.MatchLdLoc(s)
				&& TypeUtils.IsCompatibleTypeForMemoryAccess(v.Type, inst2.Type)
				&& inst2.UnalignedPrefix == 0
				&& !inst2.IsVolatile
				&& inst2.Value is DefaultValue))
			{
				return false;
			}
			context.Step("LdLocaDupInitObjTransform", inst1);
			block.Instructions[i] = new StLoc(v, inst2.Value).WithILRange(inst2);
			block.Instructions[i + 1] = inst1;
			return true;
		}
	}
}
